package com.nulldev.util.internal.backport.httpclient_rw.httpclient;

import java.net.URI;
import java.net.URL;

import com.nulldev.util.internal.backport.httpclient_rw.WebSocket;
import com.nulldev.util.web.HttpClient.providers.websockets.HttpWebSocket;
import com.nulldev.util.web.HttpClient.providers.websockets.HttpWebSocketRequest;
import com.nulldev.util.web.URLUtils.Entry;

public class BackportedWebSocketRequest implements HttpWebSocketRequest {

	private volatile WebSocket.Builder builder;
	private volatile URI url;

	public BackportedWebSocketRequest() {
		this.builder = BackportedHttpRequest.client.newWebSocketBuilder();
	}

	@Override
	public HttpWebSocketRequest url(String url) {
		try {
			this.url = new URI(url);
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
		return this;
	}

	@Override
	public HttpWebSocketRequest url(URL url) {
		try {
			this.url = url.toURI();
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
		return this;
	}

	@Override
	public HttpWebSocketRequest url(URI url) {
		this.url = url;
		return this;
	}

	@Override
	public HttpWebSocketRequest header(final String key, final String value) {
		if (key == null || key.isEmpty() || value == null)
			return this;
		this.builder = this.builder.header(key, value);
		return this;
	}

	@Override
	public HttpWebSocketRequest header(final Entry entry) {
		if (entry == null || !entry.isValid())
			return this;
		this.builder = this.builder.header(entry.getKey(), entry.getValue());
		return this;
	}

	@Override
	public HttpWebSocketRequest headers(final Entry... es) {
		if (es == null || es.length == 0)
			return this;
		for (final Entry e : es) {
			if (e.isValid())
				this.builder = this.builder.header(e.getKey(), e.getValue());
		}
		return this;
	}

	@Override
	public HttpWebSocket make() throws Exception {
		return new BackportedWebSocket(this.builder, this.url);
	}

}
